<template>
  <div class="saas-factory">
    <div class="page-header">
      <h2>SaaS工厂</h2>
      <a-space>
        <a-button type="primary" @click="createApplication">
          构建应用
        </a-button>
        <a-button @click="openTemplates"> 业态模板 </a-button>
      </a-space>
    </div>

    <!-- 应用概览 -->
    <a-row :gutter="16" style="margin-bottom: 16px">
      <a-col :span="6">
        <a-card>
          <Statistic
            title="已构建应用"
            :value="statistics.totalApplications"
            :value-style="{ color: '#3f8600' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <Statistic
            title="运行中应用"
            :value="statistics.runningApplications"
            :value-style="{ color: '#1890ff' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <Statistic
            title="可用模板"
            :value="statistics.availableTemplates"
            :value-style="{ color: '#722ed1' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <Statistic
            title="本月部署"
            :value="statistics.monthlyDeployments"
            :value-style="{ color: '#cf1322' }"
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 应用列表 -->
    <a-card title="我的应用">
      <a-table
        :columns="columns"
        :data-source="applications"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'industryType'">
            <a-tag :color="getIndustryColor(record.industryType)">
              {{ getIndustryLabel(record.industryType) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusLabel(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'environment'">
            <a-tag :color="getEnvironmentColor(record.deployment.environment)">
              {{ getEnvironmentLabel(record.deployment.environment) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="viewApplication(record)">查看</a>
              <a @click="deployApplication(record)">部署</a>
              <a @click="configApplication(record)">配置</a>
              <a @click="monitorApplication(record)">监控</a>
              <a-popconfirm
                title="确定要删除这个应用吗？"
                @confirm="deleteApplication(record.id)"
              >
                <a class="text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 构建应用模态框 -->
    <a-modal
      v-model:open="buildModalVisible"
      title="构建SaaS应用"
      width="800px"
      @ok="handleBuildSubmit"
      @cancel="handleBuildCancel"
    >
      <a-form :model="buildForm" layout="vertical">
        <a-form-item label="应用名称" name="name">
          <a-input
            v-model:value="buildForm.name"
            placeholder="请输入应用名称"
          />
        </a-form-item>
        <a-form-item label="应用描述" name="description">
          <a-textarea v-model:value="buildForm.description" :rows="3" />
        </a-form-item>
        <a-form-item label="业态类型" name="industryType">
          <a-select
            v-model:value="buildForm.industryType"
            placeholder="选择业态类型"
          >
            <a-select-option value="hotel">酒店</a-select-option>
            <a-select-option value="pet">宠物</a-select-option>
            <a-select-option value="education">教育</a-select-option>
            <a-select-option value="retail">零售</a-select-option>
            <a-select-option value="restaurant">餐饮</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="模板选择" name="templateId">
          <a-select
            v-model:value="buildForm.templateId"
            placeholder="选择构建模板"
          >
            <a-select-option value="hotel-basic">酒店基础版</a-select-option>
            <a-select-option value="hotel-premium">酒店高级版</a-select-option>
            <a-select-option value="pet-basic">宠物基础版</a-select-option>
            <a-select-option value="education-basic"
              >教育基础版</a-select-option
            >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 部署应用模态框 -->
    <a-modal
      v-model:open="deployModalVisible"
      title="部署SaaS应用"
      width="800px"
      @ok="handleDeploySubmit"
      @cancel="handleDeployCancel"
    >
      <a-form
        ref="deployFormRef"
        :model="deployForm"
        :rules="deployRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="应用名称">
              <a-input :value="deployForm.applicationName" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="应用版本" name="version">
              <a-input
                v-model:value="deployForm.version"
                placeholder="请输入版本号"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="部署环境" name="environment">
          <a-radio-group v-model:value="deployForm.environment">
            <a-radio value="dev">开发环境</a-radio>
            <a-radio value="staging">测试环境</a-radio>
            <a-radio value="prod">生产环境</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="部署区域" name="region">
          <a-select
            v-model:value="deployForm.region"
            placeholder="请选择部署区域"
          >
            <a-select-option value="cn-hangzhou">华东1（杭州）</a-select-option>
            <a-select-option value="cn-beijing">华北1（北京）</a-select-option>
            <a-select-option value="cn-shanghai">华东2（上海）</a-select-option>
            <a-select-option value="cn-shenzhen">华南1（深圳）</a-select-option>
            <a-select-option value="cn-chengdu">西南1（成都）</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="资源配置" name="resources">
          <a-card size="small" title="计算资源">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="CPU核心数">
                  <a-input-number
                    v-model:value="deployForm.resources.cpu"
                    :min="1"
                    :max="32"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="内存大小(GB)">
                  <a-input-number
                    v-model:value="deployForm.resources.memory"
                    :min="1"
                    :max="128"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="存储大小(GB)">
                  <a-input-number
                    v-model:value="deployForm.resources.storage"
                    :min="10"
                    :max="1000"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form-item>

        <a-form-item label="域名配置" name="domain">
          <a-input
            v-model:value="deployForm.domain"
            placeholder="请输入域名（可选）"
            addon-after=".saas-platform.com"
          />
        </a-form-item>

        <a-form-item label="环境变量" name="envVars">
          <a-textarea
            v-model:value="deployForm.envVars"
            placeholder="请输入环境变量配置（JSON格式）"
            :rows="4"
          />
        </a-form-item>

        <a-form-item label="部署策略" name="strategy">
          <a-radio-group v-model:value="deployForm.strategy">
            <a-radio value="rolling">滚动部署</a-radio>
            <a-radio value="blue-green">蓝绿部署</a-radio>
            <a-radio value="canary">金丝雀部署</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 部署进度模态框 -->
    <a-modal
      v-model:open="deployProgressVisible"
      title="部署进度"
      :footer="null"
      :closable="false"
      width="600px"
    >
      <div class="deploy-progress">
        <a-steps :current="deployProgress.current" direction="vertical">
          <a-step
            title="准备部署环境"
            :description="deployProgress.steps[0].description"
          />
          <a-step
            title="构建应用镜像"
            :description="deployProgress.steps[1].description"
          />
          <a-step
            title="部署应用实例"
            :description="deployProgress.steps[2].description"
          />
          <a-step
            title="配置网络和域名"
            :description="deployProgress.steps[3].description"
          />
          <a-step
            title="健康检查和启动"
            :description="deployProgress.steps[4].description"
          />
        </a-steps>

        <div class="progress-log" v-if="deployProgress.logs.length > 0">
          <h4>部署日志</h4>
          <div class="log-content">
            <div
              v-for="(log, index) in deployProgress.logs"
              :key="index"
              class="log-item"
              :class="log.type"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 应用配置组件 -->
    <ApplicationConfig
      v-model:visible="configModalVisible"
      :application="selectedApplication"
      @saved="handleConfigSaved"
    />

    <!-- 应用监控组件 -->
    <ApplicationMonitor
      v-model:visible="monitorModalVisible"
      :application="selectedApplication"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Statistic } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import {
  getSaaSApplications,
  getSAASStatistics,
  createSaaSApplication,
  deployApplication,
  getDeployStatus,
  getDeployLogs,
} from '#/api/resource-center';
import ApplicationConfig from './components/ApplicationConfig.vue';
import ApplicationMonitor from './components/ApplicationMonitor.vue';

// 响应式数据
const router = useRouter();
const loading = ref(false);
const buildModalVisible = ref(false);
const deployModalVisible = ref(false);
const deployProgressVisible = ref(false);
const deployFormRef = ref();
const configModalVisible = ref(false);
const monitorModalVisible = ref(false);
const selectedApplication = ref(null);

const statistics = ref({
  totalApplications: 0,
  runningApplications: 0,
  availableTemplates: 0,
  monthlyDeployments: 0,
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

const buildForm = reactive({
  name: '',
  description: '',
  industryType: '',
  templateId: '',
});

const deployForm = reactive({
  applicationId: '',
  applicationName: '',
  version: '1.0.0',
  environment: 'dev',
  region: 'cn-hangzhou',
  resources: {
    cpu: 2,
    memory: 4,
    storage: 50,
  },
  domain: '',
  envVars:
    '{\n  "NODE_ENV": "production",\n  "DB_HOST": "localhost",\n  "REDIS_HOST": "localhost"\n}',
  strategy: 'rolling',
});

const deployRules = {
  version: [{ required: true, message: '请输入版本号' }],
  environment: [{ required: true, message: '请选择部署环境' }],
  region: [{ required: true, message: '请选择部署区域' }],
};

const deployProgress = reactive({
  current: 0,
  steps: [
    { title: '准备部署环境', description: '正在准备部署环境...' },
    { title: '构建应用镜像', description: '正在构建应用镜像...' },
    { title: '部署应用实例', description: '正在部署应用实例...' },
    { title: '配置网络和域名', description: '正在配置网络和域名...' },
    { title: '健康检查和启动', description: '正在进行健康检查和启动...' },
  ],
  logs: [] as Array<{
    time: string;
    message: string;
    type: 'info' | 'success' | 'error';
  }>,
});

const applications = ref([
  {
    id: '1',
    name: '智慧酒店管理系统',
    description: '基于SaaS的酒店管理解决方案',
    industryType: 'hotel',
    status: 'running',
    deployment: {
      environment: 'prod',
      region: 'cn-hangzhou',
      domain: 'hotel.example.com',
      version: '1.0.0',
      deployedAt: '2024-01-15T10:30:00Z',
    },
    usage: {
      users: 150,
      storage: 1024,
      bandwidth: 512,
      lastActive: '2024-01-15T16:20:00Z',
    },
    createdAt: '2024-01-10T09:00:00Z',
    createdBy: 'admin',
  },
  {
    id: '2',
    name: '宠物店管理系统',
    description: '宠物店业务管理平台',
    industryType: 'pet',
    status: 'building',
    deployment: {
      environment: 'dev',
      region: 'cn-beijing',
      domain: '',
      version: '0.9.0',
      deployedAt: '',
    },
    usage: {
      users: 0,
      storage: 0,
      bandwidth: 0,
      lastActive: '',
    },
    createdAt: '2024-01-12T14:30:00Z',
    createdBy: 'admin',
  },
]);

const columns = [
  {
    title: '应用名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '业态类型',
    dataIndex: 'industryType',
    key: 'industryType',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '部署环境',
    dataIndex: ['deployment', 'environment'],
    key: 'environment',
  },
  {
    title: '版本',
    dataIndex: ['deployment', 'version'],
    key: 'version',
  },
  {
    title: '域名',
    dataIndex: ['deployment', 'domain'],
    key: 'domain',
  },
  {
    title: '部署时间',
    dataIndex: ['deployment', 'deployedAt'],
    key: 'deployedAt',
  },
  {
    title: '操作',
    key: 'action',
    width: 350,
  },
];

// 获取业态颜色
const getIndustryColor = (type: string) => {
  const colorMap = {
    hotel: 'blue',
    pet: 'green',
    education: 'purple',
    retail: 'orange',
    restaurant: 'cyan',
  };
  return colorMap[type] || 'default';
};

// 获取业态标签
const getIndustryLabel = (type: string) => {
  const labelMap = {
    hotel: '酒店',
    pet: '宠物',
    education: '教育',
    retail: '零售',
    restaurant: '餐饮',
  };
  return labelMap[type] || type;
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    building: 'orange',
    deploying: 'blue',
    running: 'green',
    stopped: 'red',
    error: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap = {
    building: '构建中',
    deploying: '部署中',
    running: '运行中',
    stopped: '已停止',
    error: '错误',
  };
  return labelMap[status] || status;
};

// 获取环境颜色
const getEnvironmentColor = (env: string) => {
  const colorMap = {
    dev: 'blue',
    staging: 'orange',
    prod: 'green',
  };
  return colorMap[env] || 'default';
};

// 获取环境标签
const getEnvironmentLabel = (env: string) => {
  const labelMap = {
    dev: '开发环境',
    staging: '测试环境',
    prod: '生产环境',
  };
  return labelMap[env] || env;
};

// 加载统计数据
const loadStatistics = async () => {
  try {
    statistics.value = {
      totalApplications: applications.value.length,
      runningApplications: applications.value.filter(
        (app) => app.status === 'running',
      ).length,
      availableTemplates: 12,
      monthlyDeployments: 8,
    };
  } catch (error) {
    message.error('加载统计数据失败');
  }
};

// 加载应用列表
const loadApplications = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
    };

    const result = await getSaaSApplications(params);
    applications.value = result.items || [];
    pagination.total = result.total || 0;
  } catch (error) {
    message.error('加载SaaS工厂数据失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 创建应用
const createApplication = () => {
  buildModalVisible.value = true;
  resetBuildForm();
};

// 打开模板
const openTemplates = () => {
  router.push('/resource-center/saas-factory/industry-template');
};

// 查看应用
const viewApplication = (record: any) => {
  message.info(`查看应用: ${record.name}`);
};

// 部署应用
const deployApplication = async (record: any) => {
  // 设置部署表单数据
  deployForm.applicationId = record.id;
  deployForm.applicationName = record.name;
  deployForm.version = record.deployment?.version || '1.0.0';
  deployForm.environment = record.deployment?.environment || 'dev';
  deployForm.region = record.deployment?.region || 'cn-hangzhou';

  // 打开部署模态框
  deployModalVisible.value = true;
};

// 配置应用
const configApplication = (record: any) => {
  selectedApplication.value = record;
  configModalVisible.value = true;
};

// 监控应用
const monitorApplication = (record: any) => {
  selectedApplication.value = record;
  monitorModalVisible.value = true;
};

// 删除应用
const deleteApplication = async (id: string) => {
  try {
    // 这里应该调用删除API
    message.success('删除成功');
    await loadApplications();
  } catch (error) {
    message.error('删除失败');
  }
};

// 提交构建
const handleBuildSubmit = async () => {
  try {
    const response = await createSaaSApplication(buildForm);
    if (response.success) {
      message.success('应用构建成功');
      buildModalVisible.value = false;
      await loadApplications();
    } else {
      message.error(response.message || '构建失败');
    }
  } catch (error) {
    message.error('操作失败');
    console.error(error);
  }
};

// 取消构建
const handleBuildCancel = () => {
  buildModalVisible.value = false;
  resetBuildForm();
};

// 提交部署
const handleDeploySubmit = async () => {
  try {
    await deployFormRef.value?.validate();

    // 关闭部署模态框，打开进度模态框
    deployModalVisible.value = false;
    deployProgressVisible.value = true;

    // 重置进度
    deployProgress.current = 0;
    deployProgress.logs = [];

    // 开始部署流程
    await startDeployment();
  } catch (error) {
    console.error('部署表单验证失败:', error);
  }
};

// 取消部署
const handleDeployCancel = () => {
  deployModalVisible.value = false;
  resetDeployForm();
};

// 重置部署表单
const resetDeployForm = () => {
  Object.assign(deployForm, {
    applicationId: '',
    applicationName: '',
    version: '1.0.0',
    environment: 'dev',
    region: 'cn-hangzhou',
    resources: {
      cpu: 2,
      memory: 4,
      storage: 50,
    },
    domain: '',
    envVars:
      '{\n  "NODE_ENV": "production",\n  "DB_HOST": "localhost",\n  "REDIS_HOST": "localhost"\n}',
    strategy: 'rolling',
  });
};

// 开始部署流程
const startDeployment = async () => {
  const addLog = (
    message: string,
    type: 'info' | 'success' | 'error' = 'info',
  ) => {
    deployProgress.logs.push({
      time: new Date().toLocaleTimeString(),
      message,
      type,
    });
  };

  try {
    // 调用部署API
    addLog('正在创建部署任务...');
    const deployResponse = await deployApplication({
      applicationId: deployForm.applicationId,
      version: deployForm.version,
      environment: deployForm.environment,
      region: deployForm.region,
      resources: deployForm.resources,
      domain: deployForm.domain,
      envVars: deployForm.envVars,
      strategy: deployForm.strategy,
    });

    if (deployResponse.code !== 0) {
      throw new Error(deployResponse.msg || '部署任务创建失败');
    }

    const deployId = deployResponse.data.id;
    addLog(`部署任务创建成功，任务ID: ${deployId}`, 'success');

    // 模拟部署进度更新
    const steps = [
      { name: '准备部署环境', duration: 2000 },
      { name: '构建应用镜像', duration: 3000 },
      { name: '部署应用实例', duration: 2500 },
      { name: '配置网络和域名', duration: 1500 },
      { name: '健康检查和启动', duration: 2000 },
    ];

    for (let i = 0; i < steps.length; i++) {
      const step = steps[i];
      addLog(`开始${step.name}...`);
      deployProgress.steps[i].description = `正在${step.name}...`;

      // 模拟步骤执行时间
      await new Promise((resolve) => setTimeout(resolve, step.duration));

      deployProgress.current = i + 1;
      deployProgress.steps[i].description = `${step.name}完成`;
      addLog(`${step.name}完成`, 'success');
    }

    // 部署完成
    addLog('🎉 应用部署成功！', 'success');
    message.success('应用部署成功！');

    // 更新应用状态
    const app = applications.value.find(
      (a) => a.id === deployForm.applicationId,
    );
    if (app) {
      app.status = 'running';
      app.deployment = {
        ...app.deployment,
        environment: deployForm.environment,
        region: deployForm.region,
        version: deployForm.version,
        domain:
          deployForm.domain ||
          `${deployForm.applicationName.toLowerCase()}.saas-platform.com`,
        deployedAt: new Date().toISOString(),deployedAtdeployedAt
      };
    }

    // 3秒后关闭进度模态框
    setTimeout(() => {
      deployProgressVisible.value = false;
    }, 3000);
  } catch (error) {
    addLog(`部署失败: ${error}`, 'error');
    message.error('部署失败，请查看日志');
  }
};

// 重置构建表单
const resetBuildForm = () => {
  Object.assign(buildForm, {
    name: '',
    description: '',
    industryType: '',
    templateId: '',
  });
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadApplications();
};

// 配置保存成功处理
const handleConfigSaved = () => {
  message.success('应用配置保存成功');
  // 可以在这里刷新应用列表或更新应用状态
};

// 生命周期
onMounted(() => {
  loadStatistics();
  loadApplications();
});
</script>

<style lang="less" scoped>
.saas-factory {
  padding: 24px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h2 {
      margin: 0;
    }
  }

  .deploy-progress {
    .progress-log {
      margin-top: 24px;
      border-top: 1px solid #f0f0f0;
      padding-top: 16px;

      h4 {
        margin-bottom: 12px;
        color: #333;
      }

      .log-content {
        max-height: 200px;
        overflow-y: auto;
        background: #fafafa;
        border: 1px solid #e8e8e8;
        border-radius: 4px;
        padding: 8px;

        .log-item {
          display: flex;
          margin-bottom: 4px;
          font-family: 'Courier New', monospace;
          font-size: 12px;

          .log-time {
            color: #666;
            margin-right: 8px;
            min-width: 80px;
          }

          .log-message {
            flex: 1;
          }

          &.info {
            color: #1890ff;
          }

          &.success {
            color: #52c41a;
          }

          &.error {
            color: #ff4d4f;
          }
        }
      }
    }
  }

  .text-danger {
    color: #ff4d4f;
  }
}
</style>
